/**
 * RuleItem
 * @authors 杨兴洲（of2502）
 * @date    2017/5/25 0025 11:15
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import React, { Component } from 'react';
import { Relax } from 'iflux2';
import { transformURL } from 'util/image';
import GaUtil from "util/ga-util";
import { Modal, message } from 'antd';
import MassInput from 'uikit/mass-input';

const getReplyType = (data) => {
    if (['page', 'goods', 'custom'].includes(data.content.split('__')[0])) {
        return 'link';
    }
    return data.type;
};
const getReplyItem = (data) => {
    if (data.type === "text") {
        let array = data.content.split('__');
        if (['page', 'goods', 'custom'].includes(array[0])) {
            return array[1]
        } else {
            return data.content;
        }
    }
    if (data.type === "image") {
        return <img src={transformURL(data.url)} alt={data.content} />;
    }
    if (data.type === "mpnews") {
        return data.title;
    }
    if (data.type === "news") {
        return data.title;
    }
};
const mediaTypes = {
    text: "文本",
    image: "图片",
    mpnews: "图文",
    news: "高级图文",
    video: "视频",
    voice: "语音",
    link: "链接"
};

@Relax
export default class FollowReplyItem extends Component {

    static defaultProps = {
        fetchFollowReply: () => void 0,
        updateFollowReply: () => void 0,
        deleteFollowReply: () => void 0,
        getMPNewsDetail: () => void 0,
        followReply: {}
    };

    constructor(props) {
        super(props);
        this.state = {
            temp: {},
            tempData: {
                type: "text",
                data: null
            },// 素材选择框的初始化
            followReply: {},
            visible: false,
        };
    }

    componentDidMount() {
        this.props.fetchFollowReply().then(data => this.setState({ followReply: data }));
    }

    render() {
        const { followReply: item, temp, tempData, visible } = this.state;
        const { updateFollowReply } = this.props;
        return (
            <div className="ReplyRuleItem">
                <div className="ReplyRuleItem-Header">
                    <h5>规则:关注后自动回复</h5>
                </div>
                <div className="ReplyRuleItem-Content">
                    <div className="ItemReplyContent">
                        <p className="ItemAutoReply">自动回复:</p>
                        {
                            !item.type ?
                                <p className="noResult-tip">还没有任何自动回复</p>
                                :
                                <ul className="reply_list_info">
                                    <li>
                                        <span>【{mediaTypes[getReplyType(item)]}】</span>
                                        {getReplyItem(item)}
                                        <a href="javascript:;" onClick={this.showDeleteConfirm}>删除</a>
                                        {
                                            getReplyType(item) == 'text'
                                                ? <a href="javascript:;" onClick={this.showMediaModal.bind(this, item)}>编辑</a>
                                                : null
                                        }

                                    </li>
                                </ul>
                        }
                        {
                            !item.type && <a className="btn-sm" onClick={this.showMediaModal.bind(this, {})}>添加回复内容</a>
                        }
                    </div>
                </div>
                <Modal
                    wrapClassName="media-modal"
                    closable={false}
                    visible={visible}
                    onOk={() => {
                        if (temp.type && temp.content) {
                            updateFollowReply(temp).then(() => {
                                this.setState({ visible: false, followReply: temp });
                                GaUtil.addEvent({eventAction: "更新关注回复", eventLabel: "自动回复", eventValue: temp.type});
                            });
                        } else {
                            message.error('请输入内容');
                        }
                    }}
                    onCancel={() => this.setState({ visible: false })}>
                    <MassInput
                        textMaxLength={600}
                        data={tempData}
                        onChange={({ type, data }) => {
                            // console.log({ type, data });
                            if (!data) return;

                            let content = "";
                            let extra = {};
                            if (type === "text") content = data;
                            if (type === "mpnews") {
                                content = data.media_id;
                                extra.title = data.content.news_item[0].title;
                            }
                            if (type === "news") {
                                content = data.id;
                                extra.title = data.articles[0].title;
                            }
                            if (type === "image") {
                                content = data.media_id;
                                extra.url = data.url;
                            }
                            if (type === "page") {
                                type = 'text';
                                content = data.type + '__' + data.data.url;
                                extra.url = data.type + '__' + data.data.url;
                            }
                            this.setState({
                                temp: { type, content, ...extra }
                            })
                        }} ref="massInput" />
                </Modal>
            </div>
        );
    }

    showDeleteConfirm = () => {
        Modal.confirm({
            title: `是否确定删除关注后回复内容?`,
            onOk: () => {
                this.props.deleteFollowReply()
                    .then(() => this.setState({
                        followReply: {},
                        tempData: {
                            type: "text",
                            data: null
                        }
                    }))
                GaUtil.addEvent({eventAction: "删除关注回复", eventLabel: "自动回复"});
            }
        });
    };

    showMediaModal = async ({ type, content, url }) => {

        if (type) {

            let data = null;

            if (type === "image") {

                data = { url, media_id: content };

            } else if (type === "mpnews") {

                const result = await this.props.getMPNewsDetail(content);

                data = { media_id: content, content: result };

            } else if (type === "text") {

                let array = content.split('__');
                if (['page', 'goods', 'custom'].includes(array[0])) {
                    type = 'page';
                    // console.log('page.url', array[1]);
                    data = { type: array[0], data: { url: array[1] } };
                } else {
                    data = content;
                }

            }

            this.setState({
                tempData: { type, data },
                visible: true
            });

            setTimeout(() => this.refs.massInput.update({ type, data }), 1);

        } else {

            this.setState({
                tempData: { type: 'text', data: '' },
                visible: true
            });

            setTimeout(() => this.refs.massInput.init(), 1);

        }

    }

}